﻿using HCQ2_Common.Constant;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;

namespace HCQ2_Common.Attributes
{
    /// <summary>
    ///  参数验证特性
    /// </summary>
    public class VRServiceValidAttribute: ActionFilterAttribute
    {
        /// <summary>
        /// 在调用操作方法之前发生。
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ModelStateDictionary modelState = actionContext.ModelState;
            if (modelState.IsValid)
                return;
            //验证不通过
            List<string> messList = new List<string>();
            foreach (var s in modelState.Values)
            {
                foreach (var p in s.Errors)
                {
                    string message = p.ErrorMessage;
                    if (string.IsNullOrEmpty(message))
                        message =  p.Exception.Message.ToString();
                    messList.Add(message);
                }
            }
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK,
                            new HCQ2_Model.ViewModel.WebAPI.WebApiResultJsonModel()
                            {
                                errcode = WebResultCode.Exception,
                                errmsg = GlobalConstant.参数异常.ToString(),
                                value = messList
                            });
        }
    }
}
